package com.zoe.app.dynamic;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zoe.Zhang
 * @date 2023/02/24
 * @description
 */
public class DynamicDataSourceRouter extends AbstractRoutingDataSource {
    public DynamicDataSourceRouter(DynamicDataSourceProvider dynamicDataSourceProvider) {
        Map<String, DataSource> dataSourceMap = dynamicDataSourceProvider.loadDataSourceMap();
        Map<Object, Object> stringDataSourceHashMap = new HashMap<>(dataSourceMap);
        setTargetDataSources(stringDataSourceHashMap);
        setDefaultTargetDataSource(dataSourceMap.get(DynamicDataSourceProvider.MASTER));
        afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSource();
    }
}
